<?php
namespace app\admin\service;

use exception\FriendlyException;
use app\admin\model\AdminModel;
use util\PasswordHash;
use util\SqlUtil;
use security\UserDetails;
use security\UserDetailsService;
use Exception;

/**
 * 用户信息管理
 */
class AdminService implements UserDetailsService {

    /**
     * 创建管理员
     */
    public static function create($data) {
        $mobile = $data['mobile'];
        $password = $data['password'];

        if((new AdminModel)->hasByKey('mobile', $mobile)) throw new FriendlyException('用户名已存在');

        $salt = PasswordHash::createSalt($mobile);
        $encryptPassword = PasswordHash::encrypt_password($password, $salt);
        $admin = (new AdminModel)->createOne([
            'mobile' =>  $mobile,
            'password' =>  $encryptPassword,
            'salt' =>  $salt,
            'status' => AdminModel::STATUS_NORMAL,
            'realname' =>  $data['realname'],
            'avatar_url' => '/static/avatar.png',
            'department_id' => $data['department_id'],
            'company_id' => $data['company_id'],
            'birthday' => isset($data['birthday']) ? $data['birthday'] : '',
            'rzday' => isset($data['rzday']) ? $data['rzday'] : '',
            'create_time' => SqlUtil::timestampToDatetime(),
            'last_login_time' => SqlUtil::timestampToDatetime(),
            'role_ids' => empty($data['role_ids']) ? [] : $data['role_ids'],
        ]);
        return $admin;
    }

    /**
     * 更新管理员
     */
    public static function update($data) {
        $admin = (new AdminModel)->findOne($data['id']);
        if(!$admin) throw new FriendlyException('用户不存在');
        $newData = [];
        if(isset($data['status'])) $newData['status'] = $data['status'];
        if(isset($data['realname'])) $newData['realname'] = $data['realname'];
        if(isset($data['mobile'])) $newData['mobile'] = $data['mobile'];
        if(isset($data['department_id'])) $newData['department_id'] = $data['department_id'];
        if(isset($data['company_id'])) $newData['company_id'] = $data['company_id'];
        if(isset($data['birthday'])) $newData['birthday'] = $data['birthday'];
        if(isset($data['role_ids'])) $newData['role_ids'] = $data['role_ids'];
        $admin->save($newData);
    }

    /**
     * 更新管理员密码
     */
    public function updatePassword(UserDetails $user, string $newPassword) {
        $admin = (new AdminModel)->findOne($user['id']);
        if(!$admin) throw new FriendlyException('用户不存在');
        $encryptPassword = PasswordHash::encrypt_password($newPassword, $admin['salt']);
        $admin->save([
            'password' => $encryptPassword
        ]);
    }

    /**
     * 更新管理员最后登录时间
     */
    public static function updateLoginTime($id) {
         AdminModel::update([
            'id' => $id,
            'last_login_time' => SqlUtil::datetime()
        ]);
    }

    /**
     * 删除管理员
     */
    public static function delete($id) {
        $admin = (new AdminModel)->findOne($id);
        if($admin['is_super'] == 1) {
            throw new FriendlyException('不能删除超级管理员');
        }
        return AdminModel::destroy($id);
    }

    public function loadUserByUsername(string $username): UserDetails {
        throw new Exception();
    }

    public function addCustomAuthorities(string $username, array $authorities) {}

    public function changePassword(string $oldPassword, string $newPassword) {}

    public function createUser(UserDetails $user) {}

    public function updateUser(UserDetails $user) {}

    public function userExists(string $username): bool{ return false;}

    public function deleteUser(string $username){}
}
